package com.example.kk.netty.netty;

import android.os.Handler;
import android.widget.TextView;

import com.example.kk.netty.MainActivity;
import com.example.kk.netty.netty.HelloClientInitializer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HelloClient {
	public static String host = "192.168.3.29";
	public static int port = 7946;
	Channel ch;
	private  Handler handler;
	public HelloClient() {
		// TODO Auto-generated constructor stub
	}

	public HelloClient(Handler  handler) {
		// TODO Auto-generated constructor stub
		this.handler=handler;
	}

	/**
	 * @param
	 * @throws InterruptedException
	 * @throws IOException
	 */
	public void run() throws InterruptedException, IOException {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).handler(new HelloClientInitializer(handler));
			// 连接服务端
			ch = b.connect(host, port).sync().channel();
			ch.closeFuture().sync(); // 异步关闭，这方法执行完不关闭连接

		} finally {
			// The connection is closed automatically on shutdown.
			group.shutdownGracefully();
		}
	}

	public void sendMSg(String line) {
		/*
		 * 向服务端发送在控制台输入的文本 并用"\r\n"结尾 之所以用\r\n结尾 是因为我们在handler中添加了 DelimiterBasedFrameDecoder 帧解码。
		 * 这个解码器是一个根据\n符号位分隔符的解码器。所以每条消息的最后必须加上\n否则无法识别和解码
	 */
		ch.writeAndFlush(line + "\r\n");


	}

	public void closeChannel(){
		ch.close();
	}

}